from fastapi import APIRouter, Request, HTTPException
from typing import Dict
from app.database import get_db
from app.models.concrete import Concrete
from sqlalchemy.orm import Session

router = APIRouter()

@router.post("/receive/concrete")
async def receive_concrete_data(request: Request, data: Dict):
    try:
        # 获取 source header
        source = request.headers.get("source")
        if not source:
            raise HTTPException(status_code=400, detail="Source header is required")

        # 添加 source 到数据中
        data["source"] = source

        # 获取数据库会话
        db = next(get_db())
        try:
            # 创建 Concrete 实例并保存到数据库
            db_item = Concrete(**data)
            db.add(db_item)
            db.commit()
        except Exception as db_error:
            db.rollback()
            raise HTTPException(status_code=500, detail=f"Database error: {str(db_error)}")
        finally:
            db.close()

        return {"code": 200, "message": "success"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 